# coding=utf-8
"""
    参数校验装饰器

    这里只是设计一个参数校验的装饰器
    校验时的 Schema 需要单独定义
"""
from enum import Enum

# @Time    :  2024-10-17 10:54:18
# @Author  :  jiangtong
# @Email   :  gingerqgyy@outlook.com
# @Project :  ginger_yl_test_boost
# @File    :  validators

from functools import wraps
from flask import request
from marshmallow import ValidationError
from base.base_res import res_param, res_param_info


class ParameType(Enum):
    JSON = 'json'
    FORM = 'form'
    ARGS = 'args'


# 通用校验装饰器 :
def validate_request(schema=None, source: ParameType = ParameType.JSON):
    """
    :param schema: marshmallow schema for validation, 参数校验
    :param source: (json, form, args) --> json
    """

    def decorator(func):
        @wraps(func)
        def decorated_function(*args, **kwargs):
            # 获取请求参数, ( json / form / url 拼接 )
            if source == ParameType.JSON:
                data = request.get_json(silent=True)
            elif source == ParameType.FORM:
                data = request.form.to_dict()
            elif source == ParameType.ARGS:
                data = request.args.to_dict()
            else:
                return res_param()

            # 参数校验 :
            if schema:
                try:
                    schema().load(data)
                except ValidationError as err:
                    # 响应具体校验错误的信息 :
                    return res_param_info(result=err.messages)
            return func(*args, **kwargs)

        return decorated_function

    return decorator
